package com.dodo.blog.server.impl;

import com.comvai.services.persistence.LowLevel;
import com.comvai.services.persistence.PersistenceManager;
import com.comvai.services.persistence.criteria.Criteria;
import com.comvai.services.persistence.criteria.Restrictions;
import com.dodo.blog.model.Tag;
import com.dodo.blog.request.BasicRequest;
import com.dodo.blog.server.TagService;

import javax.inject.Inject;
import java.util.List;

/**
 * @author <a href="mailto:pohorelec@comvai.com">Jozef Pohorelec</a>
 */
public class TagServiceBean
        extends AbstractServiceBean
        implements TagService
{
    @Inject
    public TagServiceBean( @LowLevel PersistenceManager datastore )
    {
        super( datastore );
    }

    @Override
    public List<Tag> getTagList( BasicRequest request )
    {
        Criteria<Tag> criteria = Criteria.create( Tag.class );
        processCriteria( criteria, request );

        return datastore.list( criteria );
    }

    @Override
    public void saveTag( Tag tag )
    {
        // TODO: check for normalized name unique

        save( tag );
    }

    @Override
    public Tag getTagById( Long id )
    {
        return datastore.find( Tag.class, id );
    }

    @Override
    public Tag getTagByNormalizedName( String name )
    {
        Criteria<Tag> criteria = Criteria.create( Tag.class );
        criteria.addCriteria( Restrictions.eq( "normalizedName", name ) );

        List<Tag> list = datastore.list( criteria );
        return list.isEmpty() ? null : list.get( 0 );
    }

    @Override
    public void deleteTag( Long id )
    {
        delete( Tag.class, id );
    }
}